import { DataType } from './config'
import { IsNotNull } from './core'
/** 格式数据为百分比
 * @param num 原数据 0.122 (此处数据是需要乘以100的数据)
 * @param { isDecimal = true } 是否取自定义的定制的小数位
 * @param { decimals = 2 } 最低保留小数位数
 * @param { isRound = false } 是否四舍五入
 * @returns 返回百分比的数据 12.20%
 */
interface Percent {
  num: DataType
  isDecimals?: false
  decimals?: number
  isRound?: boolean
}
const FormatPercent = (opt: Percent) => {
  const { num, isDecimals, decimals, isRound } = {
    ...{ isRound: false, isDecimals: true, decimals: 2 },
    ...opt,
  }
  const n = (num + '').replace(/[^0-9+-Ee.]/g, '')
  const number = !IsNotNull(n) ? +0 : +n
  const dec = Math.floor(Math.abs(decimals))
  const dot = (number * 100).toString().split('.')[1]
  let decimal = isDecimals ? dec : dot ? dot.length : 0
  decimal = decimal <= 2 ? decimal : dec
  if (isRound) {
    return (number * 100).toFixed(decimal) + '%'
  } else {
    const end =
      String(number).lastIndexOf('.') == -1
        ? 0
        : String(number).lastIndexOf('.')
    const res = decimal
      ? (number * 100).toFixed(decimal + 1).substring(0, end + (decimal + 2))
      : number * 100
    return res + '%'
  }
}
export default FormatPercent
